package com.lagou.edu.controller;

import com.lagou.edu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/register/{email}/{password}/{code}")
    public String register(@PathVariable("email")String email, @PathVariable("password")String password, @PathVariable("code")String code) {
        return userService.register(email, password, code);
    }

    @RequestMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email")String email) {
        return userService.isRegistered(email);
    }

    @RequestMapping("/login/{email}/{password}")
    public String login(@PathVariable("email")String email, @PathVariable("password")String password, HttpServletResponse response) {
        String result = userService.login(email, password);
        if(StringUtils.isNotBlank(result)) {
            log.info("用户: {} 登录成功", email);
            String token = userService.loadToken(email);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
//            cookie.setDomain("localhost");
            cookie.setMaxAge(36000);
            response.addCookie(cookie); //将token写入Cookie中
        }
        return result;
    }

    @RequestMapping("/info/{token}")
    public String info(@PathVariable("token")String token) {
        return userService.info(token);
    }
}
